package com.qianbei.view;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.qianbei.R;
import com.qianbei.bean.DriverRequestBean;
import com.qianbei.bean.VehicelRequestBean;
import com.qianbei.bean.RequeastBean1;
import com.qianbei.bean.SearchBean;
import com.qianbei.bean.VehicelResultBean;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.okhttp.RequeastBean;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.view.adapter.SearchAdapter;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * <pre>
 *     author : pwj
 *     e-mail : xxx@xx
 *     time   : 2019/03/20
 *     desc   : 搜索司机和车辆
 *     version: 1.0
 * </pre>
 */
public class SearchActivity extends BaseActivity {
    public static final String EXTRA_IS_DRIVER = "extra_is_driver";
    public static final String EXTAR_TYPE_ID = "extar_type_id";
    public static final String RESULT_DATA = "extra_data";
    public static final int CODE_RESULT_DRIVER = 200;
    public static final int CODE_RESULT_VEHICLE = 201;
    @Bind(R.id.et_search)
    EditText etSearch;
    @Bind(R.id.listView)
    PullToRefreshListView listView;
    private SearchAdapter searchAdapter;
    private int page = 1;
    private boolean isLastPage = false;
    private Gson gson = new Gson();
    private boolean isDriver;
    private String typeId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        isDriver = getIntent().getBooleanExtra(EXTRA_IS_DRIVER, false);
        typeId = getIntent().getStringExtra(EXTAR_TYPE_ID);
        if (isDriver) {
            mTitle.setTitle("请选择司机");
            etSearch.setHint("请输入司机名称");
        } else {
            mTitle.setTitle("请选择车辆");
            etSearch.setHint("请输入车牌号");
        }
        searchAdapter = new SearchAdapter(this);
        listView.setMode(PullToRefreshBase.Mode.BOTH);
        listView.setAdapter(searchAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SearchBean searchBean = searchAdapter.getItem(position-1);
                Intent intent = new Intent();
                intent.putExtra(RESULT_DATA, searchBean);
                setResult(isDriver ? CODE_RESULT_DRIVER : CODE_RESULT_VEHICLE, intent);
                finish();
            }
        });
        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (isDriver) {
                    loadDrivers(true);
                } else {
                    loadVehicles(true);
                }
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (isLastPage) {
                    new MsgAlert().show("已经是最后一页了");
                    listView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            listView.onRefreshComplete();
                        }
                    }, 500);
                } else {
                    if (isDriver) {
                        loadDrivers(false);
                    } else {
                        loadVehicles(false);
                    }
                }
            }
        });
        autoRefresh();
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    page = 1;
                    autoRefresh();
                    hintKeyboard();
                    return true;
                }
                return false;
            }
        });
    }


    private void autoRefresh() {
        listView.postDelayed(new Runnable() {
            @Override
            public void run() {
                listView.setRefreshing();
            }
        }, 100);
    }
    private void hintKeyboard() {
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        if(imm.isActive()&&getCurrentFocus()!=null){
            if (getCurrentFocus().getWindowToken()!=null) {
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }
    private void loadVehicles(final boolean isRefresh) {
        if (isRefresh) {
            page = 1;
        } else {
            if (!isLastPage) {
                page++;
            }
        }
        VehicelRequestBean vehicelRequestBean = new VehicelRequestBean();
        vehicelRequestBean.setVehicleNumber(etSearch.getText().toString().trim());
        vehicelRequestBean.set_pageSize(10);
        vehicelRequestBean.set_sortField("_id");
        vehicelRequestBean.set_number(1);
        vehicelRequestBean.set_page(page);
        RequeastBean1 bean1 = new RequeastBean1("selectByPage",
                "com.cygps.dubbo.commons.data.ICommonDataService",vehicelRequestBean,"WT_VehicleEquipment");
        ServerControl sc = new ServerControl(bean1);
        sc.serverListener = new ServerControl.ServerListener() {
            @Override
            public void serverFinish(ServerResult sr) {
                if (sr.isContinue) {
                    try {
                        String json = sr.bodyData.toString();
                        VehicelResultBean vehicelSearchBean = gson.fromJson(json, VehicelResultBean.class);
                        if (vehicelSearchBean.total > page * 10) {
                            isLastPage = false;
                        } else {
                            isLastPage = true;
                        }
                        List<SearchBean> seachBeans = vehicelSearchBean.array;
                        if (isRefresh) {
                            searchAdapter.setDatas(seachBeans);
                        } else {
                            searchAdapter.addAll(seachBeans);
                        }
                        listView.onRefreshComplete();
                    } catch (JsonSyntaxException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        sc.OKpost1();
    }

    private void loadDrivers(final boolean isRefresh) {
        if (isRefresh) {
            page = 1;
        } else {
            if (!isLastPage) {
                page++;
            }
        }
        DriverRequestBean driverRequestBean = new DriverRequestBean();
        driverRequestBean.setPersonName(etSearch.getText().toString().trim());
        driverRequestBean.set_pageSize(10);
        driverRequestBean.set_sortField("_id");
        driverRequestBean.set_number(1);
        driverRequestBean.set_page(page);
        //司机的角色id是固定的。这些接口都是f12网页上的
        driverRequestBean.setRole("5be534525b76b121143343b3");
//        driverRequestBean.setBusinessType(typeId);
        RequeastBean bean = new RequeastBean("selectByPage",
                "com.cygps.dubbo.WasteTransport.IAccount",driverRequestBean);
        ServerControl sc = new ServerControl(bean);
        sc.serverListener = new ServerControl.ServerListener() {
            @Override
            public void serverFinish(ServerResult sr) {
                if (sr.isContinue) {
                    try {
                        String json = sr.bodyData.toString();
                        VehicelResultBean vehicelSearchBean = gson.fromJson(json, VehicelResultBean.class);
                        if (vehicelSearchBean.total > page * 10) {
                            isLastPage = false;
                        } else {
                            isLastPage = true;
                        }
                        List<SearchBean> seachBeans = vehicelSearchBean.array;
                        if (isRefresh) {
                            searchAdapter.setDatas(seachBeans);
                        } else {
                            searchAdapter.addAll(seachBeans);
                        }
                        listView.onRefreshComplete();
                    } catch (JsonSyntaxException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        sc.OKpost();
    }
}
